package cn.zmit.kuxi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.GoodsDetailActivity;
import cn.zmit.kuxi.activity.LoginActivity;
import cn.zmit.kuxi.activity.NowJoinActivity;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.entity.GoodsEnity;
import cn.zmit.kuxi.holder.GoodsCamarHolder;
import cn.zmit.kuxi.interfaces.OnListItemSelectListener;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.functions.holder.ListViewDataAdapter;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.loadmore.LoadMoreContainer;
import com.xdroid.widget.loadmore.LoadMoreDefaultFooterView;
import com.xdroid.widget.loadmore.LoadMoreHandler;
import com.xdroid.widget.loadmore.LoadMoreListViewContainer;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class GoodsFragmentCammer extends Fragment {
	@ViewInject(R.id.list_goods)
	private ListView list_goods;
	private ListViewDataAdapter<GoodsEnity> goodsAdapter;
	View fragment_goods_view;
	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	/**
	 * 页码
	 */
	private int mPage = 1;
	@ViewInject(R.id.load_more_list_view_container)
	private LoadMoreListViewContainer mLoadMoreListViewContainer;
	Boolean haslog;
	private String userid;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (fragment_goods_view == null) {
			fragment_goods_view = inflater.inflate(R.layout.fragment_goods,
					container, false);
		}
		mGoodsList = new ArrayList<GoodsEnity>();
		ViewUtils.inject(this, fragment_goods_view);
		initView();
		initPtr();// 下拉刷新
//		 getDate();
		initLoadMore();
		haslog = PreferenceHelper.readBoolean(getActivity(),
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (haslog) {
			userid = PreferenceHelper.readString(getActivity(),
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}
		Button btn_gotop = (Button) fragment_goods_view.findViewById(R.id.btn_gotop);
		btn_gotop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				list_goods.setSelection(0);
				initPtr();
			}
		});
		return fragment_goods_view;
	}

	private void getDate() {
		RequestTask.getInstance().getAllGoods(getActivity(), mPage + "", "3",
				new onRequestListener());
	}

	/**
	 * 初始化上拉刷新，分页显示
	 */
	private void initLoadMore() {
		mFooterView = mLoadMoreListViewContainer.useDefaultFooterRe();
		mLoadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {

			@Override
			public void onLoadMore(LoadMoreContainer loadMoreContainer) {
				if (!mLoadMoreListViewContainer.isLoadError()) {
					mPage++;
				}
				LogUtils.i("加载更多--->page:" + mPage);
				getDate();
			}
		});
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(getActivity());
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						mFooterView.setVisibility(View.GONE);
						goodsAdapter.removeAll();
						mPage = 1;
						getDate();
					}

				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						list_goods, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	/**
	 * 请求
	 */
	private JsonData data;
	private List<GoodsEnity> mGoodsList;
	private LoadMoreDefaultFooterView mFooterView;

	private class onRequestListener extends OnRequestListenerAdapter<Object> {

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			ptr_view.refreshComplete();
//			goodsAdapter.removeAll();
			Boolean mIsEmpty = false; // 是否是空数据
			Boolean mHasMore = false; // 是否有更多数据待加载
			JsonData jsonData = JsonData.create(response);

			if (jsonData != null && jsonData.length() > 0) {
				data = jsonData.optJson("goods");
				if (data.length() > 0) {
					if (data.length() == 8) {
						mHasMore = true; // 有更多数据
					} else if (data.length() < 8) {
						mIsEmpty = false; // 有数据
						mHasMore = false; // 无更多数据
					}
					for (int i = 0; i < data.length(); i++) {
						JsonData itemDate = data.optJson(i);
						String join_count = itemDate.optString("buy_count");
						String title = itemDate.optString("phase");
						String goods = itemDate.optString("name");
						String allNeed = itemDate.optString("price");
						String gp_id = itemDate.optString("gp_id");
						String goods_id = itemDate.optString("goods_id");
						String pic = itemDate.optString("pic");
						
						GoodsEnity goodsEnity = new GoodsEnity(title, goods,
								allNeed, join_count, pic, goods_id, gp_id);
						// mGoodsList.add(goodsEnity);
						goodsAdapter.append(goodsEnity);
					}
				} else {
					// ToastUtils.show(getActivity(), "请求失败");
					mIsEmpty = true; // 空数据
					mHasMore = false; // 无更多数据
				}
				mLoadMoreListViewContainer.loadMoreFinish(mIsEmpty, mHasMore); // 判断是否加载更多
			}

		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();

		}

	}

	/**
	 * 初始化
	 */
	private void initView() {
		goodsAdapter = new ListViewDataAdapter<GoodsEnity>();
		TextView mHolderPlace = new TextView(getActivity()); // 占位作用，无意义，占据90dp高度，目的Listview位置向下移动45dp
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
				AbsListView.LayoutParams.MATCH_PARENT,
				(int) ScreenUtils.dpToPx(getActivity(), 1));
		mHolderPlace.setLayoutParams(layoutParams);
		list_goods.addHeaderView(mHolderPlace);// 为Listview添加占位符*/
		goodsAdapter.setViewHolderClass(this, GoodsCamarHolder.class);
		GoodsCamarHolder
				.setOnListItemSelectListener(new OnListItemSelectListener<GoodsEnity>() {
					@Override
					public void onlistItemSelect(int position,
							GoodsEnity itemDate) {

						Intent intent = new Intent();
						Bundle bundle = new Bundle();
						bundle.putString("gp_id", itemDate.getGp_id());
						intent.putExtras(bundle);
						intent.setClass(getActivity(),
								GoodsDetailActivity.class);
						startActivity(intent);

					}
				});
		list_goods.setAdapter(goodsAdapter);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// RequestTask.getInstance().getAllGoods(getActivity(),"3", new
		// onRequestListener());
	}
}
